package com.aleyn.mvvm.utils;

import android.app.Activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created on 2019-05-08.
 */

public class ActivityCollector {
    public static List<Activity> activities = new ArrayList<Activity>();

    public static void addActivity(Activity activity) {
        activities.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public static void finishAll() {
        for (Activity activity : activities) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    public static void finishActivity(Class<?> clazz) {
        if (activities != null) {
            // 使用迭代器安全删除
            for (Iterator<Activity> it = activities.iterator(); it.hasNext(); ) {
                Activity activity = it.next();
                // 清理掉已经释放的activity
                if (activity == null) {
                    it.remove();
                    continue;
                }
                if (activity.getClass().equals(clazz)) {
                    it.remove();
                    activity.finish();
                }
            }
        }
    }


    public static Activity getCurrentActivity() {
        return activities.get(activities.size() - 1);
    }
}
